package com.zzx.boot.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//注册组件
@Component
//@Data和@ConfigurationProperties结合使用用于在yaml中对其常量进行注入
@Data
@ConfigurationProperties("jwt.data")
@Slf4j
public class JWTUtil {


        //密钥
        public String SECRET;
        //Authorization
        private String header;

        //创建token
        //传入userid
        public String createToken(Long userId,Integer time){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND,time);
            JwtBuilder builder = Jwts.builder()
                    .setHeaderParam("typ","JWT")
                    .setSubject(userId+"")
                    .setIssuedAt(new Date())
                    .setExpiration(calendar.getTime())
                    .signWith(SignatureAlgorithm.HS256,SECRET);
            return builder.compact();
        }

        //校验jwt
        public Claims parseToken(String token){
                return Jwts.parser()
                        .setSigningKey(SECRET)
                        .parseClaimsJws(token)
                        .getBody();

        }

        //判断token是否过期
        public boolean judgeTokenExpiration(Date expiration){
            return expiration.before(new Date());
        }


}

